
const ROLE = require("../../../model/role-model");
const { getFilter } = require("../../../utils/setFilter");
const { deletePermisson } = require("../../r_role_permission");
const deleteCorrelation = require("./r_role_user").deleteDocuments;


// add role
const addRole = async ({ roleName }) => {

    try {
        const queryRole = await ROLE.findOne({ roleName });
        if (queryRole !== null) {
            return {
                status: "0001",
                message: "已经有此角色组了",
            }
        }


        // 可以添加
        const res = await ROLE.create({ roleName })
        return {
            status: "0000",
            message: "添加成功",
            data: {
                _id: res._id,
                roleId: res._id,
                roleName: res.roleName
            }
        }
    } catch (error) {
        return {
            status: "1001",
            message: "服务故障"
        }
    }




}

// get list
const getRoleList = async ({ roleName, roleId }) => {
    
    try {
        let params = {
            _id: roleId && { $eq: roleId },
            roleName: roleName && { $regex: eval("/" + roleName + "/i") }
        }
        params = getFilter(params);

        const res = await ROLE.find(params).sort({ createDate: 1 })
        return res;
    } catch (error) {
        return {
            status: "1001",
            message: "服务故障"
        }
    }
}

const deleteDocuments = async ({ ids = [] }) => {
    const deleteResult = await ROLE.deleteMany({
        _id: { $in: ids }
    });
    if (deleteResult.deletedCount) {
        //同时也删除（角色用户关系表）中的数据.
        deleteCorrelation({ roleIds: ids }).then((res) => {
            console.log(res)
        })
        deletePermisson({ role_id: ids }).then(res => {

        })
        return {
            status: '0000',
            message: `删除了${deleteResult.deletedCount}条数据`
        }
    } else {
        return {
            status: '0010',
            message: `删除失败`
        }
    }
}




module.exports = {
    addRole, getRoleList, deleteDocuments
}